﻿using Microsoft.Xna.Framework.Graphics;
using RilattackLibrary;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using System;
using System.Linq;
using System.Windows.Threading;
using System.Threading;
using System.Collections.Generic;
using System.Reflection;
using System.Timers;

namespace RilattackGameWPF
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class RilattackGame : Game
    {
        public static RilattackGame Instance { get; set; }
        public GameConfiguration Configuration;
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        System.Timers.Timer gameLoopTimer;

        public RilattackGame()
        {
            gameLoopTimer = new System.Timers.Timer();
            gameLoopTimer.Elapsed += new ElapsedEventHandler(this.gameLoop);
            gameLoopTimer.Interval = 10;

            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            Instance = this;
            
        }

        //void xnaWinForm_ResizeBegin(object sender, EventArgs e)
        //{
        //    isDraging = true;
        //    Console.WriteLine("Draggg");
        //}

        //void xnaWinForm_ResizeEnd(object sender, EventArgs e)
        //{
        //    isDraging = false;
        //    Console.WriteLine("Dropppp");
        //}

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
            App.Server.CallForInit();
		}

		/// <summary>
		/// LoadContent will be called once per game and is the place to load
		/// all of your content.
		/// </summary>
		protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            Scene.Instance.Textures.Add("tiles1", Content.Load<Texture2D>("tiles1"));
            Scene.Instance.Textures.Add("Worms/wblink1", Content.Load<Texture2D>("Worms/wblink1"));
            Scene.Instance.Initialize();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (!gameLoopTimer.Enabled)
                gameLoopTimer.Enabled = true;
            base.Update(gameTime);
    	}

        private void MooveGraphicObject(GraphicObject graphicObject)
        {
            Rectangle rect = new Rectangle(graphicObject.Dest.X + graphicObject.MovementDirection.x, graphicObject.Dest.Y, Player.playerW, Player.playerH);
            List<MapTile> mapTiles = Map.FindMapTilesByPosition(Scene.Instance.Actors, rect);

            if (IsOnlyEmptyBlocks(mapTiles))
            {
                graphicObject.AplyXMovementDirection();
            }


            rect = new Rectangle(graphicObject.Dest.X, graphicObject.Dest.Y + graphicObject.MovementDirection.y, Player.playerW, Player.playerH);
            mapTiles = Map.FindMapTilesByPosition(Scene.Instance.Actors, rect);

            if (IsOnlyEmptyBlocks(mapTiles))
            {
                graphicObject.AplyYMovementDirection();
            }
        }

        private Boolean IsOnlyEmptyBlocks(List<MapTile> mapTiles)
        {
            if (null != mapTiles && mapTiles.Count > 0)
            {
                return false;
            }

            return true;
        }


		/// <summary>
		/// This is called when the game should draw itself.
		/// </summary>
		/// <param name="gameTime">Provides a snapshot of timing values.</param>
		protected override void Draw(GameTime gameTime)
        {

            GraphicsDevice.Clear(Color.CornflowerBlue);

            Scene.Instance.Act(spriteBatch);

            base.Draw(gameTime);
        }

        private void gameLoop(object source, ElapsedEventArgs e)
        {
            int posX, posY;
            float speed = 10f;
            float deltaTime = System.Environment.TickCount;

            if (deltaTime >= 0.02f)
                deltaTime = 0.02f;

            //Console.WriteLine("Delta: " + deltaTime.ToString());
            //Console.WriteLine("Player Pos: x-" + App.Client.CurrentPlayer.Dest.X + " y-" + App.Client.CurrentPlayer.Dest.Y);

            App.Client.CurrentPlayer.MovementDirection.x = (int)((App.Client.CurrentPlayer.MovementDirection.x * speed) * speed * deltaTime);
            App.Client.CurrentPlayer.MovementDirection.y = (int)(((App.Client.CurrentPlayer.MovementDirection.y + Scene.Gravity) * speed) * speed * deltaTime);

            if (Scene.Instance != null && Scene.Instance.Actors != null)
            {
                MooveGraphicObject(App.Client.CurrentPlayer);
            }

            App.Client.CurrentPlayer.GetPosition(out posX, out posY);
            App.Server.RequestUpdate(posX, posY);
            App.Server.RequestUpdate(posX, posY);
        }
    }
}